//
//  HomeViewController.swift
//  banTang
//
//  Created by 王磊 on 17/4/7.
//  Copyright © 2017年 王磊. All rights reserved.
//

import UIKit
import SwiftyJSON

class HomeViewController: RootViewController {
    
    var vcArray = Array<SegmentViewController>()
    var tableViewArray = Array<UITableView>()
    
    var topicArray = Array<TopicModel>()
    
    var currentTableView = UITableView()
    
    var lastTableViewOffsetY = CGFloat()
    
    
    
    lazy var navView: NavView = {
        let nav = NavView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 64))
        nav.backgroundColor = UIColor.clear
        return nav
    }()
    lazy var headScrollView: HeadScrollView = {
        let headScroll = HeadScrollView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 200))
        return headScroll
    }()
    lazy var headSegmentView: HeadSegmentView = {
        let headSeg = HeadSegmentView.init(frame: CGRect.init(x: 0, y: 200, width: SCREEN_WIDTH, height: 40))
        headSeg.deleaget = self
        return headSeg
    }()
    
    lazy var bottomScroll: UIScrollView = {
        let scroll = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        scroll.showsHorizontalScrollIndicator = false
        scroll.isPagingEnabled = true
        scroll.delegate = self
        for i in 0...headSegmentArray.count-1 {
            
            let segVC = SegmentViewController()
            segVC.view.frame = CGRect.init(x: SCREEN_WIDTH * CGFloat(i), y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
            scroll.addSubview(segVC.view)
            self.vcArray.append(segVC)
            self.tableViewArray.append(segVC.tableView)
            
            segVC.tableView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
        }
        scroll.contentSize = CGSize.init(width: CGFloat(headSegmentArray.count) * SCREEN_WIDTH, height: SCREEN_HEIGHT)
        return scroll
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.addSubview(self.bottomScroll)
        self.navView.tableViews = self.tableViewArray
        
        self.view.addSubview(self.headScrollView)
        self.view.addSubview(self.headSegmentView)
        
        self.view.addSubview(self.navView)
        
        getScrollImage()
        loadData()
        
    }
    
    
    /// 获取数据
    func loadData() {
        
        
        let para = ["app_id":"com.jzyd.BanTang",
                    "app_installtime":"1482905598",
                    "app_versions":"5.9.5",
                    "channel_name":"appStore",
                    "client_id":"bt_app_ios",
                    "client_secret":"9c1e6634ce1c5098e056628cd66a17a5",
                    "oauth_token":"4150e754a624ecdc255ad1d13f6287bc",
                    //"last_get_time":"1463238932",
            "os_versions":"10.2",
            "screensize":"750",
            "track_device_info":"iPhone8,4",
            "track_device_uuid":"DE964894-8C6F-48BF-9F6C-A47167353EAC",
            "track_deviceid":"BAEA9AD2-16E3-4D12-8E28-4EB9F15A1412",
            "track_user_id":"2777434",
            "v":"24",
            "page":"0",
            "pagesize":"20"
        ]
        
        
        NetRequest.sharedInstance.getRequest(urlString: "http://open3.bantangapp.com/recommend/index?", params: para) {(resonse, error) in
            
            let json = JSON(resonse!)
            //print(json)
            
            
            for (_,subJson) : (String,JSON) in json["data"]["topic"] {
                
                let model = TopicModel.init(dic: subJson)
                
                self.topicArray.append(model)
            }
            for vc: SegmentViewController in self.vcArray {
                
                vc.dataSource = self.topicArray
                vc.tableView.reloadData()
            }
        }
    }
    
    func getScrollImage() {
        
        var array = Array<BannerModel>()
        var titleArray = Array<String>()
        
        
        let para = ["app_id":"com.jzyd.BanTang",
                    "app_installtime":"1482905598",
                    "app_versions":"5.9.5",
                    "channel_name":"appStore",
                    "client_id":"bt_app_ios",
                    "client_secret":"9c1e6634ce1c5098e056628cd66a17a5",
                    "oauth_token":"4150e754a624ecdc255ad1d13f6287bc",
                    //"last_get_time":"1463238932",
            
            "os_versions":"10.2",
            "screensize":"750",
            "track_device_info":"iPhone8,4",
            "track_device_uuid":"DE964894-8C6F-48BF-9F6C-A47167353EAC",
            "track_deviceid":"BAEA9AD2-16E3-4D12-8E28-4EB9F15A1412",
            "track_user_id":"2777434",
            "v":"24",
            "page":"0",
            "pagesize":"20"
        ]
        
        NetRequest.sharedInstance.getRequest(urlString: "http://open3.bantangapp.com/recommend/operationElement?", params: para, finished: {(response,error) in
            
            let json = JSON(response!)
            
            for (_,subJson) : (String,JSON) in json["data"]["banner"] {
                
                let model = BannerModel.init(dic: subJson)
                
                array.append(model)
            }
            for (_,subJson) : (String,JSON) in json["data"]["category_element"] {
                
                let model = CategoryModel.init(dic: subJson)
                
                titleArray.append(model.title)
            }
            
            self.headScrollView.getScrollImgSource(source: array)
            self.headSegmentView.sendData(array: titleArray)
            
        })
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let tableView = object as! UITableView
        
        if !(keyPath == "contentOffset") {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }
        
        let tableViewoffsetY = tableView.contentOffset.y
        
        self.lastTableViewOffsetY = tableViewoffsetY
        
        if ( tableViewoffsetY >= 0 && tableViewoffsetY <= 136) {
            self.headSegmentView.frame = CGRect.init(x: 0, y: 200-tableViewoffsetY, width: SCREEN_WIDTH, height: 40)
            self.headScrollView.frame = CGRect.init(x: 0, y: 0-tableViewoffsetY, width: SCREEN_WIDTH, height: 200);
            
        }else if( tableViewoffsetY < 0){
            self.headSegmentView.frame = CGRect.init(x: 0, y: 200, width: SCREEN_WIDTH, height:40);
            self.headScrollView.frame = CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 200);
            
        }else if (tableViewoffsetY > 136){
            self.headSegmentView.frame = CGRect.init(x: 0, y: 64, width: SCREEN_WIDTH, height:40);
            self.headScrollView.frame = CGRect.init(x: 0, y: -136, width: SCREEN_WIDTH, height: 200);
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension HomeViewController: HeadSegmentViewDelegate {
    
    func clickSegment(index: NSInteger) {
        
        self.currentTableView = self.tableViewArray[0]
        
        for table: UITableView in self.tableViewArray {
            if ( self.lastTableViewOffsetY>=0 &&  self.lastTableViewOffsetY<=136) {
                table.contentOffset = CGPoint.init(x: 0, y: self.lastTableViewOffsetY)
                
            }else if(  self.lastTableViewOffsetY < 0){
                table.contentOffset = CGPoint.init(x: 0, y: 0)
                
            }else if ( self.lastTableViewOffsetY > 136){
                table.contentOffset = CGPoint.init(x: 0, y: 136)
            }
            
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            
            self.bottomScroll.contentOffset = CGPoint.init(x: SCREEN_WIDTH * CGFloat(index), y: 0)
        })
        
    }
}

extension HomeViewController:UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.headSegmentView.getIndex(index: Int(scrollView.contentOffset.x / SCREEN_WIDTH))
        
        self.currentTableView = self.tableViewArray[Int(scrollView.contentOffset.x / SCREEN_WIDTH)]
        
        for table: UITableView in self.tableViewArray {
            if ( self.lastTableViewOffsetY>=0 &&  self.lastTableViewOffsetY<=136) {
                table.contentOffset = CGPoint.init(x: 0, y: self.lastTableViewOffsetY)
                
            }else if(  self.lastTableViewOffsetY < 0){
                table.contentOffset = CGPoint.init(x: 0, y: 0)
                
            }else if ( self.lastTableViewOffsetY > 136){
                table.contentOffset = CGPoint.init(x: 0, y: 136)
            }
            
        }
        
        
    }
}

